/**
 * @class DutyList.calendar.form.EventWindow
 * @extends Ext.Window
 * <p>A custom window containing a basic edit form used for quick editing of events.</p>
 * <p>This window also provides custom events specific to the calendar so that other calendar components can be easily
 * notified when an event has been edited via this component.</p>
 * @constructor
 * @param {Object} config The config object
 */
Ext.define('DutyList.calendar.form.SheduleWindow', {
    extend: 'Ext.window.Window',
    alias: 'widget.usereditwindow',
    
    requires: [
        'Ext.form.Panel',
        'DutyList.calendar.data.SheduleModel',
        'DutyList.calendar.data.SheduleMappings'
    ],

    constructor: function(config) {
        var formPanelCfg = {
            xtype: 'form',
            fieldDefaults: {
                msgTarget: 'side',
                labelWidth: 30
            },
            frame: false,
            bodyStyle: 'background:transparent;padding:5px 10px 10px;',
            bodyBorder: false,
            border: false,
            items: [{
                itemId: 'title',
                name: DutyList.calendar.data.SheduleMappings.Name.name,
                fieldLabel: 'Title',
                xtype: 'textfield',
                anchor: '100%'
            },
            {
                xtype: 'daterangefield',
                itemId: 'date-range',
                name: 'dates',
                anchor: '100%',
                fieldLabel: 'Date'
            }]
        };

        this.callParent([Ext.apply({
            titleTextAdd: 'Add User',
            titleTextEdit: 'Edit User',
            width: 400,
            autocreate: true,
            border: true,
            closeAction: 'hide',
            modal: false,
            resizable: true,
            buttonAlign: 'left',
            layout: 'fit',
    
            fbar: [
                '->',
            {
                itemId: 'delete-btn',
                text: 'Delete User',
                disabled: false,
                handler: this.onDelete,
                scope: this,
                minWidth: 150,
                hideMode: 'offsets'
            },
            {
                text: 'Save',
                disabled: false,
                handler: this.onSave,
                scope: this
            },
            {
                text: 'Cancel',
                disabled: false,
                handler: this.onCancel,
                scope: this
            }],
            items: formPanelCfg
        },
        config)]);
    },

    // private
    newId: 10000,

    // private
    initComponent: function() {
        this.callParent();

        this.formPanel = this.items.items[0];

        this.addEvents({
            /**
             * @event eventadd
             * Fires after a new event is added
             * @param {DutyList.calendar.form.EventWindow} this
             * @param {DutyList.calendar.EventRecord} rec The new {@link DutyList.calendar.EventRecord record} that was added
             */
            eventadd: true,
            /**
             * @event eventupdate
             * Fires after an existing event is updated
             * @param {DutyList.calendar.form.EventWindow} this
             * @param {DutyList.calendar.EventRecord} rec The new {@link DutyList.calendar.EventRecord record} that was updated
             */
            eventupdate: true,
            /**
             * @event eventdelete
             * Fires after an event is deleted
             * @param {DutyList.calendar.form.EventWindow} this
             * @param {DutyList.calendar.EventRecord} rec The new {@link DutyList.calendar.EventRecord record} that was deleted
             */
            eventdelete: true,
            /**
             * @event eventcancel
             * Fires after an event add/edit operation is canceled by the user and no store update took place
             * @param {DutyList.calendar.form.EventWindow} this
             * @param {DutyList.calendar.EventRecord} rec The new {@link DutyList.calendar.EventRecord record} that was canceled
             */
            eventcancel: true
        });
    },

    // private
    afterRender: function() {
        this.callParent();

        this.el.addCls('ext-cal-event-win');

        this.titleField = this.down('#title');
        this.dateRangeField = this.down('#date-range');
        this.deleteButton = this.down('#delete-btn');

        this.titleField.isValid = function() {
            return this.getValue().length > 0;
        };
    },

    show: function(o, animateTarget) {
        var me = this,
            anim = (Ext.isIE8 && Ext.isStrict) ? null: animateTarget,
            M = DutyList.calendar.data.SheduleMappings;
        this.callParent([anim, function(){
            me.titleField.focus(true, 100);
        }]);
        if (o.updateObj===true){
            this.activeRecord = o.rec;
            o = {data :{
                Night : o.Night,
                StartDate : o.StartDate,
                Name : this.activeRecord.data.Name,
                SheduleId : this.activeRecord.data.SheduleId

            }}
            this.activeRecord.updateObj = true;
        }

        this.deleteButton[o.data && o.data[M.SheduleId.name] ? 'show': 'hide']();

        var rec,
        f = this.formPanel.form;
        if (o.data) {
            rec = o;
            this.setTitle(rec.phantom ? this.titleTextAdd : this.titleTextEdit);
            f.loadRecord(rec);//переопределить попожже метод для загрузки данных в форму
        }
        else {
            this.setTitle(this.titleTextAdd);

            var startDate = o[M.StartDate.name],

            rec = Ext.create('DutyList.calendar.data.SheduleModel');
            rec.data[M.StartDate.name] = startDate;
            rec.data[M.Night.name]=anim.indexOf('nighttime')>-1;
            f.reset();
            f.loadRecord(rec);
        }
        this.dateRangeField.setDT(rec.data[M.StartDate.name]);
        this.dateRangeField.setNight(rec.data[M.Night.name]);
        this.activeRecord = (this.activeRecord && this.activeRecord.updateObj ? this.activeRecord : rec);

        return this;
    },

    // private
    onCancel: function() {
        this.cleanup(true);
        this.fireEvent('eventcancel', this);
    },

    // private
    cleanup: function(hide) {
        if (this.activeRecord && this.activeRecord.dirty) {
            this.activeRecord.reject();
        }
        delete this.activeRecord;

        if (hide === true) {
            // Work around the CSS day cell height hack needed for initial render in IE8/strict:
            //var anim = afterDelete || (Ext.isIE8 && Ext.isStrict) ? null : this.animateTarget;
            this.hide();
        }
    },

    // private
    updateRecord: function(record, keepEditing) {
        var fields = record.fields,
            values = this.formPanel.getForm().getValues(),
            name,
            M = DutyList.calendar.data.SheduleMappings,
            obj = {};
        fields.each(function(f) {
            name = f.name;
            if (name in values) {
                obj[name] = values[name];
            }
        });
        
        //var dates = this.dateRangeField.getDT();
        var dates = this.dateRangeField.getValue();
        obj[M.StartDate.name] = dates[0];
        obj[M.Night.name] = dates[1];

        record.beginEdit();
        record.set(obj);
        
        if (!keepEditing) {
            record.endEdit();
        }

        return this;
    },
    
    // private
    onSave: function(){
        if(!this.formPanel.form.isValid()){
            return;
        }
        if(!this.updateRecord(this.activeRecord)){
            this.onCancel();
            return;
        }
        this.fireEvent(this.activeRecord.phantom ? 'eventadd' : 'eventupdate', this, this.activeRecord, this.animateTarget);

        // Clear phantom and modified states.
        this.activeRecord.commit();
    },
    
    // private
    onDelete: function(){
        this.fireEvent('eventdelete', this, this.activeRecord, this.animateTarget);
    }
});